package com.guo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guo.common.ErrorCode;
import com.guo.constant.UserConstant;
import com.guo.exception.BusinessException;
import com.guo.mapper.UserMapper;
import com.guo.model.domain.User;
import com.guo.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* @author gwj
* @description 用户服务实现类
* @createDate 2024-07-09 13:26:43
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    private static final String SALT = "gwj";

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword,String planetCode) {
        //校验
      if(StringUtils.isAnyBlank(userAccount,userPassword,checkPassword,planetCode)){
          throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
      }
      if(planetCode.length()>5){
          throw new BusinessException(ErrorCode.PARAMS_ERROR,"星球id大于5位");
      }
      if (userAccount.length()<4){
          throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号小于4位");
      }
      if(userPassword.length()<8 || checkPassword.length()<8){
          throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码小于8位");
      }
      if(!StringUtils.equals(userPassword,checkPassword)){
          throw new BusinessException(ErrorCode.PARAMS_ERROR,"两次密码不相同");
      }
        String regex = "^[a-zA-Z0-9@._-]*[^@._-][a-zA-Z0-9@._-]*$";
        Matcher matcher = Pattern.compile(regex).matcher(userAccount);
        if(!matcher.find()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码含有非法字符");
      }
        //账号不能重复
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("userAccount",userAccount);
        Long count = baseMapper.selectCount(userQueryWrapper);
        if(count>0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号重复");
        }
        //星球code不能重复
        QueryWrapper<User> codeQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("planetCode",planetCode);
        Long planetCodeCount = baseMapper.selectCount(userQueryWrapper);
        if(planetCodeCount>0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"星球编码不能重复");
        }

        //加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setPlanetCode(planetCode);
        boolean save = this.save(user);
        if(!save){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"注册失败");
        }
        return user.getId();
    }

    @Override
    public User doLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //校验
        if(StringUtils.isAnyBlank(userAccount,userPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");

        }
        if (userAccount.length()<4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户长度小于4位");

        }
        if(userPassword.length()<8 ){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户密码小于8位");

        }

        String regex = "^[a-zA-Z0-9@._-]*[^@._-][a-zA-Z0-9@._-]*$";
        Matcher matcher = Pattern.compile(regex).matcher(userAccount);
        if(!matcher.find()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码还有非法字符");

        }
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper
                .eq("userAccount",userAccount)
                .eq("userPassword",encryptPassword);
        User user = baseMapper.selectOne(userQueryWrapper);
        if(user==null){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"登录失败");

        }
        User safetyUser = getSafetyUser(user);
        //记录用户的登录状态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE,safetyUser);
        return safetyUser;
    }

    /**
     * 用户脱敏
     * @param user
     * @return safetyUser
     */
    @Override
    public User getSafetyUser(User user){
        //用户信息脱敏
        User safetyUser = new User();
        safetyUser.setId(user.getId());
        safetyUser.setUsername(user.getUsername());
        safetyUser.setUserPassword("");
        safetyUser.setUserAccount(user.getUserAccount());
        safetyUser.setAvatarUrl(user.getAvatarUrl());
        safetyUser.setGender(user.getGender());
        safetyUser.setPhone(user.getPhone());
        safetyUser.setEmail(user.getEmail());
        safetyUser.setUserRole(user.getUserRole());
        safetyUser.setPlanetCode(user.getPlanetCode());
        safetyUser.setUserStatus(user.getUserStatus());
        safetyUser.setCreateTime(user.getCreateTime());
        return safetyUser;
    }

    /**
     * 用户退出
     * @return
     */
    @Override
    public int userLogout(HttpServletRequest request) {
        request.removeAttribute(UserConstant.USER_LOGIN_STATE);
        return 1;
    }


}




